﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using NUnit.Framework;
using Smith.AMC;
using Smith.AMC.Configuration;
using Smith.AMC.Network;

namespace MemcachedClientTests
{
    [TestFixture]
    public class GetsTest
    {
        private List<KeyValuePair<IPAddress, int>> servers = new List<KeyValuePair<IPAddress, int>>();
        private ServerNodeMonitorConfiguration config = new ServerNodeMonitorConfiguration();

        [TestFixtureSetUp]
        public void PerTestSetUp()
        {
            servers.Add(new KeyValuePair<IPAddress, int>(IPAddress.Parse("127.0.0.1"), 11211));
        }

        [Test]
        public void GetsShouldRetrieveTheCASValue()
        {
            ServerPool pool = new ServerPool(servers, SocketType.Stream, ProtocolType.Tcp, 25, config);
            MemcachedClient client = new MemcachedClient(new SocketWorker(pool, TimeSpan.FromSeconds(20)));

            ICacheItem<long> cacheItem = new CacheItem<long>
            {
                CacheKey = Guid.NewGuid().ToString(),
                LifeTime = TimeSpan.FromSeconds(0),
                Value = 1234567890
            };

            ManualResetEvent evt = new ManualResetEvent(false);

            client.BeginSet(cacheItem, ar =>
            {
                ManualResetEvent evtInner = (ManualResetEvent)ar.AsyncState;
                try
                {
                    client.EndSet<long>(ar);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                evtInner.Set();
            }, evt);
            evt.WaitOne();
            ManualResetEvent evt2 = new ManualResetEvent(false);
            ICacheItem<long> itemRetrieved = null;
            client.BeginGets<long>(cacheItem.CacheKey, ar =>
            {
                ManualResetEvent evtInner = (ManualResetEvent)ar.AsyncState;
                try
                {
                    itemRetrieved = client.EndGets<long>(ar);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
                evtInner.Set();
            }, evt2);
            evt2.WaitOne();

            Assert.IsNotNull(itemRetrieved);
            Assert.That(itemRetrieved.CASValue, Is.GreaterThan(0));
                
        }
    }
}
